%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import sqlite3
import pandas as pd
import numpy as np
import nltk
import string
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import confusion_matrix
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
from nltk.stem.porter import PorterStemmer
import re
# Tutorial about Python regular expressions: https://pymotw.com/2/re/
import string
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from gensim.models import Word2Vec
from gensim.models import KeyedVectors
import pickle
from tqdm import tqdm
import os
from chart_studio.plotly import plotly
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
from collections import Counter
project_data = pd.read_csv("train_data.csv", nrows = 75000)
resource_data = pd.read_csv("resources.csv", nrows = 75000)
print("Number of data points in train data", project_data.shape)
print('-'*50)
print("The attributes of data :", project_data.columns.values)
# Let's check for any "null" or "missing" values
project_data.info()
project_data['teacher_prefix'].isna().sum()
# "teacher_prefix" seems to contain 3 "missing" values, let't use mode replacement strategy to fill those missing values
project_data['teacher_prefix'].mode()
# Let's replace the missing values with "Mrs." , as it is the mode of the "teacher_prefix"
project_data['teacher_prefix'] = project_data['teacher_prefix'].fillna('Mrs.')
price_data = resource_data.groupby('id').agg({'price':'sum', 'quantity':'sum'}).reset_index()
project_data = pd.merge(project_data, price_data, on='id', how='left')
# Let's select only the selected features or columns, dropping "project_resource_summary" as it is optional
#
project_data.drop(['id','teacher_id','project_submitted_datetime','project_resource_summary'],axis=1, inplace=True)
project_data.columns
# Data seems to be highly imbalanced since the ratio of "class 1" to "class 0" is nearly 5.5
project_data['project_is_approved'].value_counts()
number_of_approved = project_data['project_is_approved'][project_data['project_is_approved'] == 1].count()
number_of_not_approved = project_data['project_is_approved'][project_data['project_is_approved'] == 0].count()
print("Ratio of Project approved to Not approved is:", number_of_approved/number_of_not_approved)
# merge two column text dataframe:
project_data["essay"] = project_data["project_essay_1"].map(str) +\
project_data["project_essay_2"].map(str) + \
project_data["project_essay_3"].map(str) + \
project_data["project_essay_4"].map(str)
project_data.head(2)
# Let's drop the project essay columns from the dadaset now, as we have captured the essay text data into single "essay" column
project_data.drop(['project_essay_1','project_essay_2','project_essay_3','project_essay_4'],axis=1, inplace=True)
y = project_data['project_is_approved'].values
X = project_data.drop(['project_is_approved'], axis=1)
X.head(1)
# train test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, stratify=y)
def cleaning_text_data(list_text_feature,df,old_col_name,new_col_name):
# remove special characters from list of strings python: https://stackoverflow.com/a/47301924/4084039
# https://www.geeksforgeeks.org/removing-stop-words-nltk-python/
# https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string
# https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python
feature_list = []
for i in list_text_feature:
temp = ""
# consider we have text like this "Math & Science, Warmth, Care & Hunger"
for j in i.split(','): # it will split it in three parts ["Math & Science", "Warmth", "Care & Hunger"]
if 'The' in j.split(): # this will split each of the catogory based on space "Math & Science"=> "Math","&", "Science"
j=j.replace('The','') # if we have the words "The" we are going to replace it with ''(i.e removing 'The')
j = j.replace(' ','') # we are placeing all the ' '(space) with ''(empty) ex:"Math & Science"=>"Math&Science"
temp+=j.strip()+" " #" abc ".strip() will return "abc", remove the trailing spaces
temp = temp.replace('&','_') # we are replacing the & value into
feature_list.append(temp.strip())
df[new_col_name] = feature_list
df.drop([old_col_name], axis=1, inplace=True)
from collections import Counter
my_counter = Counter()
for word in df[new_col_name].values:
my_counter.update(word.split())
feature_dict = dict(my_counter)
sorted_feature_dict = dict(sorted(feature_dict.items(), key=lambda kv: kv[1]))
return sorted_feature_dict
def clean_project_grade(list_text_feature,df,old_col_name,new_col_name):
# remove special characters from list of strings python: https://stackoverflow.com/a/47301924/4084039
# https://www.geeksforgeeks.org/removing-stop-words-nltk-python/
# https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string
# https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python
feature_list = []
for i in list_text_feature:
temp = i.split(' ')
last_dig = temp[-1].split('-')
fin = [temp[0]]
fin.extend(last_dig)
feature = '_'.join(fin)
feature_list.append(feature.strip())
df[new_col_name] = feature_list
df.drop([old_col_name], axis=1, inplace=True)
from collections import Counter
my_counter = Counter()
for word in df[new_col_name].values:
my_counter.update(word.split())
feature_dict = dict(my_counter)
sorted_feature_dict = dict(sorted(feature_dict.items(), key=lambda kv: kv[1]))
return sorted_feature_dict
x_train_sorted_category_dict = cleaning_text_data(X_train['project_subject_categories'],X_train,'project_subject_categories','clean_categories')
x_test_sorted_category_dict = cleaning_text_data(X_test['project_subject_categories'],X_test,'project_subject_categories','clean_categories')
x_train_sorted_subcategories = cleaning_text_data(X_train['project_subject_subcategories'],X_train,'project_subject_subcategories','clean_subcategories')
x_test_sorted_subcategories = cleaning_text_data(X_test['project_subject_subcategories'],X_test,'project_subject_subcategories','clean_subcategories')
x_train_sorted_grade = clean_project_grade(X_train['project_grade_category'],X_train,'project_grade_category','clean_grade')
x_test_sorted_grade = clean_project_grade(X_test['project_grade_category'],X_test,'project_grade_category','clean_grade')
# https://stackoverflow.com/a/47091490/4084039
import re
def decontracted(phrase):
# specific
phrase = re.sub(r"won't", "will not", phrase)
phrase = re.sub(r"can\'t", "can not", phrase)
# general
phrase = re.sub(r"n\'t", " not", phrase)
phrase = re.sub(r"\'re", " are", phrase)
phrase = re.sub(r"\'s", " is", phrase)
phrase = re.sub(r"\'d", " would", phrase)
phrase = re.sub(r"\'ll", " will", phrase)
phrase = re.sub(r"\'t", " not", phrase)
phrase = re.sub(r"\'ve", " have", phrase)
phrase = re.sub(r"\'m", " am", phrase)
return phrase
# https://gist.github.com/sebleier/554280
# we are removing the words from the stop words list: 'no', 'nor', 'not'
stopwords= ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've",\
"you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', \
'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their',\
'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', \
'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', \
'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', \
'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',\
'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further',\
'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more',\
'most', 'other', 'some', 'such', 'only', 'own', 'same', 'so', 'than', 'too', 'very', \
's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', \
've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn',\
"hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn',\
"mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", \
'won', "won't", 'wouldn', "wouldn't"]
# Combining all the above stundents
from tqdm import tqdm
def process_text(df,col_name):
preprocessed_feature = []
# tqdm is for printing the status bar
for sentance in tqdm(df[col_name].values):
sent = decontracted(sentance)
sent = sent.replace('\\r', ' ')
sent = sent.replace('\\"', ' ')
sent = sent.replace('\\n', ' ')
sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
# https://gist.github.com/sebleier/554280
sent = ' '.join(e for e in sent.split() if e.lower() not in stopwords)
preprocessed_feature.append(sent.lower().strip())
return preprocessed_feature
x_train_essay_preprocessed = process_text(X_train,'essay')
x_test_essay_preprocessed = process_text(X_test,'essay')
x_train_title_preprocessed = process_text(X_train,'project_title')
x_test_title_preprocessed = process_text(X_test,'project_title')
# we use count vectorizer to convert the values into one
from sklearn.feature_extraction.text import CountVectorizer
def cat_vectorizer(X_train,df,col_name):
vectorizer = CountVectorizer()
vectorizer.fit(X_train[col_name].values)
feature_one_hot = vectorizer.transform(df[col_name].values)
print(vectorizer.get_feature_names())
return feature_one_hot, vectorizer.get_feature_names()
x_train_cat_one_hot, x_train_cat_feat_list = cat_vectorizer(X_train,X_train,'clean_categories')
x_test_cat_one_hot, x_test_cat_feat_list = cat_vectorizer(X_train,X_test,'clean_categories')
# shape after categorical one hot encoding
print(x_train_cat_one_hot.shape)
print(x_test_cat_one_hot.shape)
x_train_subcat_one_hot, x_train_subcat_feat_list = cat_vectorizer(X_train,X_train,'clean_subcategories')
x_test_subcat_one_hot, x_test_subcat_feat_list = cat_vectorizer(X_train,X_test,'clean_subcategories')
# shape after categorical one hot encoding
print(x_train_subcat_one_hot.shape)
print(x_test_subcat_one_hot.shape)
# we use count vectorizer to convert the values into one hot encoding
# CountVectorizer for "school_state"
x_train_state_one_hot, x_train_state_feat_list = cat_vectorizer(X_train,X_train,'school_state')
x_test_state_one_hot, x_test_state_feat_list = cat_vectorizer(X_train,X_test,'school_state')
# shape after categorical one hot encoding
print(x_train_state_one_hot.shape)
print(x_test_state_one_hot.shape)
# we use count vectorizer to convert the values into one hot encoding
# CountVectorizer for teacher_prefix
x_train_teacher_prefix_one_hot,x_train_teacher_prefix_feat_list = cat_vectorizer(X_train,X_train,'teacher_prefix')
x_test_teacher_prefix_one_hot,x_test_teacher_prefix_feat_list = cat_vectorizer(X_train,X_test,'teacher_prefix')
# shape after categorical one hot encoding
print(x_train_teacher_prefix_one_hot.shape)
print(x_test_teacher_prefix_one_hot.shape)
# using count vectorizer for one-hot encoding of project_grade_category
x_train_grade_one_hot, x_train_grade_feat_list = cat_vectorizer(X_train,X_train,'clean_grade')
x_test_grade_one_hot, x_test_grade_feat_list = cat_vectorizer(X_train,X_test,'clean_grade')
# shape after categorical one hot encoding
print(x_train_grade_one_hot.shape)
print(x_test_grade_one_hot.shape)
from sklearn.feature_extraction.text import TfidfVectorizer
# We are considering only the words which appeared in at least 10 documents(rows or projects).
def tfidf_vectorizer(X_train,col_name,df):
vectorizer = TfidfVectorizer()
vectorizer.fit(X_train[col_name].values)
df_tfidf = vectorizer.transform(df[col_name].values)
return df_tfidf, vectorizer.get_feature_names()
# Lets vectorize essay
x_train_essay_tfidf, x_train_essay_tfidf_feat = tfidf_vectorizer(X_train,'essay',X_train)
x_test_essay_tfidf, x_test_essay_tfidf_feat = tfidf_vectorizer(X_train,'essay',X_test)
print(x_train_essay_tfidf.shape)
print(x_test_essay_tfidf.shape)
from sklearn.feature_extraction.text import TfidfVectorizer
# We are considering only the words which appeared in at least 10 documents(rows or projects).
def tfidf_vectorizer_title(X_train,col_name,df):
vectorizer = TfidfVectorizer()
vectorizer.fit(X_train[col_name].values)
df_tfidf = vectorizer.transform(df[col_name].values)
return df_tfidf, vectorizer.get_feature_names()
# Lets vectorize essay
x_train_title_tfidf, x_train_title_tfidf_feat = tfidf_vectorizer_title(X_train,'project_title',X_train)
x_test_title_tfidf, x_test_title_tfidf_feat = tfidf_vectorizer_title(X_train,'project_title',X_test)
print(x_train_title_tfidf.shape)
print(x_test_title_tfidf.shape)
# Combining all the above stundents
from tqdm import tqdm
def preprocess_essay(df,col_name):
preprocessed_essays = []
# tqdm is for printing the status bar
for sentance in tqdm(df[col_name].values):
sent = decontracted(sentance)
sent = sent.replace('\\r', ' ')
sent = sent.replace('\\"', ' ')
sent = sent.replace('\\n', ' ')
sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
# https://gist.github.com/sebleier/554280
sent = ' '.join(e for e in sent.split() if e not in stopwords)
preprocessed_essays.append(sent.lower().strip())
return preprocessed_essays
# average Word2Vec
# compute average word2vec for each review.
def compute_avg_W2V(preprocessed_feature):
avg_w2v_vectors = []; # the avg-w2v for each sentence/review is stored in this list
for sentence in tqdm(preprocessed_feature): # for each review/sentence
vector = np.zeros(300) # as word vectors are of zero length
cnt_words =0; # num of words with a valid vector in the sentence/review
for word in sentence.split(): # for each word in a review/sentence
if word in glove_words:
vector += model[word]
cnt_words += 1
if cnt_words != 0:
vector /= cnt_words
avg_w2v_vectors.append(vector)
return avg_w2v_vectors
x_train_preprocessed_essay = preprocess_essay(X_train,'essay')
x_test_preprocessed_essay = preprocess_essay(X_test,'essay')
x_train_preprocessed_title = preprocess_essay(X_train,'project_title')
x_test_preprocessed_title = preprocess_essay(X_test,'project_title')
# stronging variables into pickle files python: http://www.jessicayung.com/how-to-use-pickle-to-save-and-load-variables-in-python/
# make sure you have the glove_vectors file
with open('glove_vectors', 'rb') as f:
model = pickle.load(f)
glove_words = set(model.keys())
# S = ["abc def pqr", "def def def abc", "pqr pqr def"]
def get_tfidf_dict(preprocessed_feature):
tfidf_model = TfidfVectorizer()
tfidf_model.fit(preprocessed_feature)
# we are converting a dictionary with word as a key, and the idf as a value
dictionary = dict(zip(tfidf_model.get_feature_names(), list(tfidf_model.idf_)))
tfidf_words = set(tfidf_model.get_feature_names())
return dictionary, tfidf_words
# average Word2Vec
# compute average word2vec for each review.
def compute_tfidf_w2v_vectors(preprocessed_feature):
tfidf_w2v_vectors = []; # the avg-w2v for each sentence/review is stored in this list
dictionary, tfidf_words = get_tfidf_dict(preprocessed_feature)
for sentence in tqdm(preprocessed_feature): # for each review/sentence
vector = np.zeros(300) # as word vectors are of zero length
tf_idf_weight =0; # num of words with a valid vector in the sentence/review
for word in sentence.split(): # for each word in a review/sentence
if (word in glove_words) and (word in tfidf_words):
vec = model[word] # getting the vector for each word
# here we are multiplying idf value(dictionary[word]) and the tf value((sentence.count(word)/len(sentence.split())))
tf_idf = dictionary[word]*(sentence.count(word)/len(sentence.split())) # getting the tfidf value for each word
vector += (vec * tf_idf) # calculating tfidf weighted w2v
tf_idf_weight += tf_idf
if tf_idf_weight != 0:
vector /= tf_idf_weight
tfidf_w2v_vectors.append(vector)
return tfidf_w2v_vectors
x_train_weighted_w2v_essay = compute_tfidf_w2v_vectors(x_train_essay_preprocessed)
x_test_weighted_w2v_essay= compute_tfidf_w2v_vectors(x_test_essay_preprocessed)
x_train_weighted_w2v_title = compute_tfidf_w2v_vectors(x_train_title_preprocessed)
x_test_weighted_w2v_title= compute_tfidf_w2v_vectors(x_test_title_preprocessed)
We have 2 numerical features left, "price" and "teacher_number_of_previously_posted_projects". Let's check for the "missing" or "NaN" values present in those numerical features and use "Mean Replacement" for "price" and "Mode Replacement" for "teacher_number_of_previously_posted_projects".
print("Total number of \"Missing\" Values present in X_train price:",X_train['price'].isna().sum())
print("Total number of \"Missing\" Values present in X_test price:",X_test['price'].isna().sum())
print("Total number of \"Missing\" Values present in X_train previous teacher number:",X_train['teacher_number_of_previously_posted_projects'].isna().sum())
print("Total number of \"Missing\" Values present in X_test previous teacher number:",X_test['teacher_number_of_previously_posted_projects'].isna().sum())
print("Total number of \"Missing\" Values present in X_train quantity:",X_train['quantity'].isna().sum())
print("Total number of \"Missing\" Values present in X_test quantity:",X_test['quantity'].isna().sum())
"teacher_number_of_previously_posted_projects" does not have any "missing" values.
X_train['price'].mean()
X_train['price'] = X_train['price'].fillna(306.5909)
X_test['price'].mean()
X_test['price'] = X_test['price'].fillna(275.0432)
print(X_train['quantity'].mean())
print(X_test['quantity'].mean())
X_train['quantity'] = X_train['quantity'].fillna(18.5928)
X_test['quantity'] = X_test['quantity'].fillna(18.38291)
# check this one: https://www.youtube.com/watch?v=0HOqOcln3Z4&t=530s
# https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html
from sklearn.preprocessing import StandardScaler
def scaler_function(df,col_name):
scaler = StandardScaler()
scaler.fit(df[col_name].values.reshape(-1,1)) # finding the mean and standard deviation of this data
# Now standardize the data with above maen and variance.
print(f"Mean : {scaler.mean_[0]}, Standard deviation : {np.sqrt(scaler.var_[0])}")
scaled = scaler.transform(df[col_name].values.reshape(-1, 1))
return scaled
x_train_teacher_number = scaler_function(X_train,'teacher_number_of_previously_posted_projects')
x_test_teacher_number = scaler_function(X_test,'teacher_number_of_previously_posted_projects')
x_train_price = scaler_function(X_train,'price')
x_test_price = scaler_function(X_test,'price')
x_train_quantity = scaler_function(X_train,'quantity')
x_test_quantity = scaler_function(X_test,'quantity')
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
# import nltk
# nltk.download('vader_lexicon')
def compute_sentiment_score(df):
score_list = []
sid = SentimentIntensityAnalyzer()
for essay in df['essay']:
ss = sid.polarity_scores(essay)
score_list.append(ss)
return score_list
# we can use these 4 things as features/attributes (neg, neu, pos, compound)
# neg: 0.0, neu: 0.753, pos: 0.247, compound: 0.93
x_train_score = compute_sentiment_score(X_train)
x_test_score = compute_sentiment_score(X_test)
def populate_list(score_dicts):
neg_score = []
neu_score = []
pos_score = []
compound_score = []
for dict_ in score_dicts:
neg_score.append(dict_['neg'])
neu_score.append(dict_['neu'])
pos_score.append(dict_['pos'])
compound_score.append(dict_['compound'])
return neg_score, neu_score, pos_score, compound_score
x_train_neg, x_train_neu, x_train_pos, x_train_compound = populate_list(x_train_score)
x_test_neg, x_test_neu, x_test_pos, x_test_compound = populate_list(x_test_score)
# for training set
X_train['neg'] = x_train_neg
X_train['neu'] = x_train_neu
X_train['pos'] = x_train_pos
X_train['compound'] = x_train_compound
# for testing set
X_test['neg'] = x_test_neg
X_test['neu'] = x_test_neu
X_test['pos'] = x_test_pos
X_test['compound'] = x_test_compound
# merge two sparse matrices: https://stackoverflow.com/a/19710648/4084039
from scipy.sparse import hstack
# with the same hstack function we are concatinating a sparse matrix and a dense matirx :)
X_train_set_1 = hstack((x_train_cat_one_hot,x_train_subcat_one_hot,x_train_state_one_hot,x_train_teacher_prefix_one_hot,\
x_train_grade_one_hot,x_train_teacher_number,x_train_price,x_train_quantity,x_train_title_tfidf,x_train_essay_tfidf,\
X_train['neg'].values.reshape(-1,1),X_train['neu'].values.reshape(-1,1),X_train['pos'].values.reshape(-1,1),X_train['compound'].values.reshape(-1,1))).tocsr()
X_test_set_1 = hstack((x_test_cat_one_hot,x_test_subcat_one_hot,x_test_state_one_hot,x_test_teacher_prefix_one_hot,\
x_test_grade_one_hot,x_test_teacher_number,x_test_price,x_test_quantity,x_test_title_tfidf,x_test_essay_tfidf,\
X_test['neg'].values.reshape(-1,1),X_test['neu'].values.reshape(-1,1),X_test['pos'].values.reshape(-1,1),X_test['compound'].values.reshape(-1,1))).tocsr()
# https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html
# https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html
from sklearn.model_selection import GridSearchCV
from scipy.stats import randint as sp_randint
from sklearn.model_selection import RandomizedSearchCV
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score
from sklearn.tree import DecisionTreeClassifier
import math
DT_ = DecisionTreeClassifier(class_weight = "balanced")
parameters = {'max_depth':[1,5,10,50]}
clf = RandomizedSearchCV(DT_, parameters,n_iter = 4, scoring='roc_auc')
clf.fit(X_train_set_1, y_train)
results = pd.DataFrame.from_dict(clf.cv_results_)
results = results.sort_values(['param_max_depth'])
train_auc= results['mean_train_score']
train_auc_std= results['std_train_score']
cv_auc = results['mean_test_score']
cv_auc_std= results['std_test_score']
max_depth_ = results['param_max_depth'].apply(lambda x: math.log10(x))
plt.plot(max_depth_, train_auc, label='Train AUC')
plt.plot(max_depth_, cv_auc, label='CV AUC')
plt.scatter(max_depth_, train_auc, label='Train AUC points')
plt.scatter(max_depth_, cv_auc, label='CV AUC points')
plt.legend()
plt.xlabel("log10(C): hyperparameter")
plt.ylabel("AUC")
plt.title("Hyper parameter Vs AUC plot")
plt.grid()
plt.show()
results.head()
# From the AUC plot, we find that the best value for "max_depth" - for the DecisionTreeClassfier is 10
best_max_depth = 10
DT_ = DecisionTreeClassifier(class_weight = "balanced")
parameters = {'min_samples_split':[5,10,100,500]}
clf = RandomizedSearchCV(DT_, parameters,n_iter = 4, scoring='roc_auc')
clf.fit(X_train_set_1, y_train)
results = pd.DataFrame.from_dict(clf.cv_results_)
results = results.sort_values(['param_min_samples_split'])
train_auc= results['mean_train_score']
train_auc_std= results['std_train_score']
cv_auc = results['mean_test_score']
cv_auc_std= results['std_test_score']
min_samples_split_ = results['param_min_samples_split'].apply(lambda x: math.log10(x))
plt.plot(min_samples_split_, train_auc, label='Train AUC')
plt.plot(min_samples_split_, cv_auc, label='CV AUC')
plt.scatter(min_samples_split_, train_auc, label='Train AUC points')
plt.scatter(min_samples_split_, cv_auc, label='CV AUC points')
plt.legend()
plt.xlabel("log10(C): hyperparameter")
plt.ylabel("AUC")
plt.title("Hyper parameter Vs AUC plot")
plt.grid()
plt.show()
results.head()
# min_samples_split from the graph above is 500
best_min_samples_split = 500
# https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html#sklearn.metrics.roc_curve
from sklearn.metrics import roc_curve, auc
DT_ = DecisionTreeClassifier(max_depth=best_max_depth, min_samples_split = best_min_samples_split ,class_weight = "balanced")
DT_.fit(X_train_set_1, y_train)
y_train_pred = DT_.predict_proba(X_train_set_1)
y_test_pred = DT_.predict_proba(X_test_set_1)
y_train_pred_prob = []
y_test_pred_prob = []
for index in range(len(y_train_pred)):
y_train_pred_prob.append(y_train_pred[index][1])
for index in range(len(y_test_pred)):
y_test_pred_prob.append(y_test_pred[index][1])
train_fpr, train_tpr, tr_thresholds = roc_curve(y_train, y_train_pred_prob)
test_fpr, test_tpr, te_thresholds = roc_curve(y_test, y_test_pred_prob)
plt.plot(train_fpr, train_tpr, label="train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("tpr")
plt.ylabel("fpr")
plt.title("ROC PLOTS for train,test and cv ")
plt.grid()
plt.show()
def compute_auc_with_hyper_para_depth(x_tr,y_tr, x_te, y_te, depth_list):
auc_tr = []
auc_te = []
y_train_pred_prob = []
y_test_pred_prob = []
for depth in depth_list:
DT_ = DecisionTreeClassifier(max_depth = depth, class_weight = "balanced")
DT_.fit(x_tr,y_tr)
y_train_pred = DT_.predict_proba(x_tr)
y_test_pred = DT_.predict_proba(x_te)
for index in range(len(y_train_pred)):
y_train_pred_prob.append(y_train_pred[index][1])
for index in range(len(y_test_pred)):
y_test_pred_prob.append(y_test_pred[index][1])
train_fpr, train_tpr, tr_thresholds = roc_curve(y_tr, y_train_pred_prob)
test_fpr, test_tpr, tc_thresholds = roc_curve(y_te, y_test_pred_prob)
y_train_pred_prob = []
y_test_pred_prob = []
auc_tr.append(auc(train_fpr,train_tpr))
auc_te.append(auc(test_fpr,test_tpr))
plt.plot(depth_list,auc_tr,label="train_auc_with_max_depth")
plt.plot(depth_list,auc_te,label="test_auc_with_max_depth")
plt.legend()
plt.xlabel("Hyper Parameter:(max_depth)")
plt.ylabel("Area Under ROC Curve")
plt.title("auc v/s hyper parameters")
plt.grid()
plt.show()
def compute_auc_with_hyper_para_split(x_tr,y_tr, x_te, y_te, split_list):
auc_tr = []
auc_te = []
y_train_pred_prob = []
y_test_pred_prob = []
for split in split_list:
DT_ = DecisionTreeClassifier(min_samples_split = split, class_weight = "balanced")
DT_.fit(x_tr,y_tr)
y_train_pred = DT_.predict_proba(x_tr)
y_test_pred = DT_.predict_proba(x_te)
for index in range(len(y_train_pred)):
y_train_pred_prob.append(y_train_pred[index][1])
for index in range(len(y_test_pred)):
y_test_pred_prob.append(y_test_pred[index][1])
train_fpr, train_tpr, tr_thresholds = roc_curve(y_tr, y_train_pred_prob)
test_fpr, test_tpr, tc_thresholds = roc_curve(y_te, y_test_pred_prob)
y_train_pred_prob = []
y_test_pred_prob = []
auc_tr.append(auc(train_fpr,train_tpr))
auc_te.append(auc(test_fpr,test_tpr))
plt.plot(split_list,auc_tr,label="train_auc_with_min_split")
plt.plot(split_list,auc_te,label="test_auc_with_min_split")
plt.legend()
plt.xlabel("Hyper Parameter:(min_samples_split)")
plt.ylabel("Area Under ROC Curve")
plt.title("auc v/s hyper parameters")
plt.grid()
plt.show()
depth_list = [1,5,10,50]
compute_auc_with_hyper_para_depth(X_train_set_1,y_train,X_test_set_1, y_test, depth_list)
split_list = [5,10,100,500]
compute_auc_with_hyper_para_split(X_train_set_1,y_train,X_test_set_1, y_test, split_list)
# we are writing our own function for predict, with defined thresould
# we will pick a threshold that will give the least fpr
def find_best_threshold(threshould, fpr, tpr):
t = threshould[np.argmax(tpr*(1-fpr))]
# (tpr*(1-fpr)) will be maximum if your fpr is very low and tpr is very high
print("the maximum value of tpr*(1-fpr)", max(tpr*(1-fpr)), "for threshold", np.round(t,3))
return t
def predict_with_best_t(proba, threshould):
predictions = []
for i in proba:
if i>=threshould:
predictions.append(1)
else:
predictions.append(0)
return predictions
print("="*100)
from sklearn.metrics import confusion_matrix
best_t = find_best_threshold(tr_thresholds, train_fpr, train_tpr)
print("Train confusion matrix")
sns.heatmap(confusion_matrix(y_train, predict_with_best_t(y_train_pred_prob, best_t)),annot = True, fmt = "d", cbar=False)
print("Test confusion matrix")
sns.heatmap(confusion_matrix(y_test, predict_with_best_t(y_test_pred_prob, best_t)), annot = True, fmt = "d", cbar=False)
# y_test we have as y_test from train_test_split
# https://www.geeksforgeeks.org/generating-word-cloud-python/
from wordcloud import WordCloud
y_actual = y_test
# y_predicted would be
y_pred = predict_with_best_t(y_test_pred_prob, best_t)
essay_words = " "
essay_ = []
for i in range(len(y_pred)):
if y_pred[i]==1 and y_actual[i]!=y_pred[i]:
essay_.append(x_train_preprocessed_essay[i])
for essay in essay_:
essay_words += essay + " "
wordcloud = WordCloud(width = 800, height = 800,
background_color ='white',
stopwords = stopwords,
min_font_size = 10).generate(essay_words)
# plot the WordCloud image
plt.figure(figsize = (8, 8), facecolor = None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad = 0)
plt.show()
y_actual = y_test
# y_predicted would be
y_pred = predict_with_best_t(y_test_pred_prob, best_t)
prices = []
for i in range(len(y_pred)):
if y_pred[i]==1 and y_actual[i]!=y_pred[i]:
prices.append(X_train['price'].iloc[i])
fig = plt.figure(figsize=(20,10))
fig.suptitle('Price from false positive data points', fontsize=14, fontweight='bold')
ax = fig.add_subplot(111)
ax.boxplot(prices)
ax.set_ylabel('Price')
plt.show()
y_actual = y_test
# y_predicted would be
y_pred = predict_with_best_t(y_test_pred_prob, best_t)
teacher_number_ = []
for i in range(len(y_pred)):
if y_pred[i]==1 and y_actual[i]!=y_pred[i]:
teacher_number_.append(X_train['teacher_number_of_previously_posted_projects'].iloc[i])
fig = plt.figure(figsize=(20,10))
ax = sns.distplot(teacher_number_, hist=True, kde=True,
bins=int(180/5), color = 'darkblue',
hist_kws={'edgecolor':'black'},
kde_kws={'linewidth': 4})
ax.set(xlabel = 'teacher numbers of previously posted projects',ylabel = 'probabilities')
plt.show()
def enable_plotly_in_cell():
import IPython
from plotly.offline import init_notebook_mode
display(IPython.core.display.HTML('''<script src="/static/components/requirejs/require.js"></script>'''))
init_notebook_mode(connected=False)
%matplotlib inline
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
def plot_3d_plot(x_tr, y_tr, x_te, y_te, depth_list, split_list):
auc_tr = []
auc_te = []
y_train_pred_prob = []
y_test_pred_prob = []
for depth, split in zip(depth_list ,split_list):
DT_ = DecisionTreeClassifier(max_depth = depth ,min_samples_split = split, class_weight = "balanced")
DT_.fit(x_tr,y_tr)
y_train_pred = DT_.predict_proba(x_tr)
y_test_pred = DT_.predict_proba(x_te)
for index in range(len(y_train_pred)):
y_train_pred_prob.append(y_train_pred[index][1])
for index in range(len(y_test_pred)):
y_test_pred_prob.append(y_test_pred[index][1])
train_fpr, train_tpr, tr_thresholds = roc_curve(y_tr, y_train_pred_prob)
test_fpr, test_tpr, tc_thresholds = roc_curve(y_te, y_test_pred_prob)
y_train_pred_prob = []
y_test_pred_prob = []
auc_tr.append(auc(train_fpr,train_tpr))
auc_te.append(auc(test_fpr,test_tpr))
X = split_list
Y = depth_list
Z1 = auc_tr
Z2 = auc_te
# https://plot.ly/python/3d-axes/
trace1 = go.Scatter3d(x=X,y=Y,z=Z1, name = 'train')
trace2 = go.Scatter3d(x=X,y=Y,z=Z2, name = 'cv')
data = [trace1,trace2]
enable_plotly_in_cell()
layout = go.Layout(scene = dict(
xaxis = dict(title='min_samples_split'),
yaxis = dict(title='max_depth'),
zaxis = dict(title='AUC'),))
fig = go.Figure(data=data, layout=layout)
offline.iplot(fig, filename='3d-scatter-colorscale')
depth = [1,5,10,50]
split = [5,10,100,500]
plot_3d_plot(X_train_set_1, y_train, X_test_set_1, y_test, depth, split)
DT_ = DecisionTreeClassifier(max_depth = None)
clf = DT_.fit(X_train_set_1, y_train)
feat = dict(zip(X_train.columns, clf.feature_importances_))
feat
From the feature importance, we found that only "school_state","teacher_number_of_previously_posted_projects" and "price" are the important features. So we are using these features and we'll use LogisticRegression .
# lets prepare new set consisting non_zero feature importance
X_train_new = hstack((x_train_state_one_hot,x_train_teacher_number,x_train_price)).tocsr()
X_test_new = hstack((x_test_state_one_hot, x_test_teacher_number,x_test_price)).tocsr()
# https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html
# https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html
from sklearn.model_selection import GridSearchCV
from scipy.stats import randint as sp_randint
from sklearn.model_selection import RandomizedSearchCV
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score
from sklearn.linear_model import LogisticRegression
import math
log_reg = LogisticRegression(class_weight = "balanced")
parameters = {'C':[10**x for x in range(-4,5)]}
clf = RandomizedSearchCV(log_reg, parameters,n_iter = 9, scoring='roc_auc')
clf.fit(X_train_new, y_train)
results = pd.DataFrame.from_dict(clf.cv_results_)
results = results.sort_values(['param_C'])
train_auc= results['mean_train_score']
train_auc_std= results['std_train_score']
cv_auc = results['mean_test_score']
cv_auc_std= results['std_test_score']
max_depth_ = results['param_C'].apply(lambda x: math.log10(x))
plt.plot(max_depth_, train_auc, label='Train AUC')
plt.plot(max_depth_, cv_auc, label='CV AUC')
plt.scatter(max_depth_, train_auc, label='Train AUC points')
plt.scatter(max_depth_, cv_auc, label='CV AUC points')
plt.legend()
plt.xlabel("log10(C): hyperparameter")
plt.ylabel("AUC")
plt.title("Hyper parameter Vs AUC plot")
plt.grid()
plt.show()
results.head()
# best "c" for Logisticregression from the graph is 0.0001
best_C = 0.0001
# https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html#sklearn.metrics.roc_curve
log_reg = LogisticRegression(C = best_C, class_weight = "balanced")
log_reg.fit(X_train_new, y_train)
y_train_pred = log_reg.predict_proba(X_train_new)
y_test_pred = log_reg.predict_proba(X_test_new)
y_train_pred_prob = []
y_test_pred_prob = []
for index in range(len(y_train_pred)):
y_train_pred_prob.append(y_train_pred[index][1])
for index in range(len(y_test_pred)):
y_test_pred_prob.append(y_test_pred[index][1])
train_fpr, train_tpr, tr_thresholds = roc_curve(y_train, y_train_pred_prob)
test_fpr, test_tpr, te_thresholds = roc_curve(y_test, y_test_pred_prob)
plt.plot(train_fpr, train_tpr, label="train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("tpr")
plt.ylabel("fpr")
plt.title("ROC PLOTS for train,test")
plt.grid()
plt.show()
print("="*100)
best_t = find_best_threshold(tr_thresholds, train_fpr, train_tpr)
print("Train confusion matrix")
sns.heatmap(confusion_matrix(y_train, predict_with_best_t(y_train_pred_prob, best_t)),annot = True, fmt = "d", cbar=False)
print("Test confusion matrix")
sns.heatmap(confusion_matrix(y_test, predict_with_best_t(y_test_pred_prob, best_t)), annot = True, fmt = "d", cbar=False)
X_train_set_2 = hstack((x_train_cat_one_hot,x_train_subcat_one_hot,x_train_state_one_hot,x_train_teacher_prefix_one_hot,\
x_train_grade_one_hot,x_train_teacher_number,x_train_price,x_train_quantity,x_train_weighted_w2v_title,x_train_weighted_w2v_essay,\
X_train['neg'].values.reshape(-1,1),X_train['neu'].values.reshape(-1,1),X_train['pos'].values.reshape(-1,1),X_train['compound'].values.reshape(-1,1))).tocsr()
X_test_set_2 = hstack((x_test_cat_one_hot,x_test_subcat_one_hot,x_test_state_one_hot,x_test_teacher_prefix_one_hot,\
x_test_grade_one_hot,x_test_teacher_number,x_test_price,x_test_quantity,x_test_weighted_w2v_title,x_test_weighted_w2v_essay,\
X_test['neg'].values.reshape(-1,1),X_test['neu'].values.reshape(-1,1),X_test['pos'].values.reshape(-1,1),X_test['compound'].values.reshape(-1,1))).tocsr()
# https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html
# https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html
DT_ = DecisionTreeClassifier(class_weight = "balanced")
parameters = {'max_depth':[1,5,10,50]}
clf = RandomizedSearchCV(DT_, parameters,n_iter = 4, scoring='roc_auc')
clf.fit(X_train_set_2, y_train)
results = pd.DataFrame.from_dict(clf.cv_results_)
results = results.sort_values(['param_max_depth'])
train_auc= results['mean_train_score']
train_auc_std= results['std_train_score']
cv_auc = results['mean_test_score']
cv_auc_std= results['std_test_score']
max_depth_ = results['param_max_depth'].apply(lambda x: math.log10(x))
plt.plot(max_depth_, train_auc, label='Train AUC')
plt.plot(max_depth_, cv_auc, label='CV AUC')
plt.scatter(max_depth_, train_auc, label='Train AUC points')
plt.scatter(max_depth_, cv_auc, label='CV AUC points')
plt.legend()
plt.xlabel("log10(C): hyperparameter")
plt.ylabel("AUC")
plt.title("Hyper parameter Vs AUC plot")
plt.grid()
plt.show()
results.head()
# From the AUC plot, we find that the best value for "max_depth" - for the DecisionTreeClassfier is 5
best_max_depth = 5
DT_ = DecisionTreeClassifier(class_weight = "balanced")
parameters = {'min_samples_split':[5,10,100,500]}
clf = RandomizedSearchCV(DT_, parameters,n_iter = 4, scoring='roc_auc')
clf.fit(X_train_set_2, y_train)
results = pd.DataFrame.from_dict(clf.cv_results_)
results = results.sort_values(['param_min_samples_split'])
train_auc= results['mean_train_score']
train_auc_std= results['std_train_score']
cv_auc = results['mean_test_score']
cv_auc_std= results['std_test_score']
min_samples_split_ = results['param_min_samples_split'].apply(lambda x: math.log10(x))
plt.plot(min_samples_split_, train_auc, label='Train AUC')
plt.plot(min_samples_split_, cv_auc, label='CV AUC')
plt.scatter(min_samples_split_, train_auc, label='Train AUC points')
plt.scatter(min_samples_split_, cv_auc, label='CV AUC points')
plt.legend()
plt.xlabel("log10(C): hyperparameter")
plt.ylabel("AUC")
plt.title("Hyper parameter Vs AUC plot")
plt.grid()
plt.show()
results.head()
# min_samples_split from the graph above is 500
best_min_samples_split = 500
# https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html#sklearn.metrics.roc_curve
from sklearn.metrics import roc_curve, auc
DT_ = DecisionTreeClassifier(max_depth=best_max_depth, min_samples_split = best_min_samples_split ,class_weight = "balanced")
DT_.fit(X_train_set_2, y_train)
y_train_pred = DT_.predict_proba(X_train_set_2)
y_test_pred = DT_.predict_proba(X_test_set_2)
y_train_pred_prob = []
y_test_pred_prob = []
for index in range(len(y_train_pred)):
y_train_pred_prob.append(y_train_pred[index][1])
for index in range(len(y_test_pred)):
y_test_pred_prob.append(y_test_pred[index][1])
train_fpr, train_tpr, tr_thresholds = roc_curve(y_train, y_train_pred_prob)
test_fpr, test_tpr, te_thresholds = roc_curve(y_test, y_test_pred_prob)
plt.plot(train_fpr, train_tpr, label="train AUC ="+str(auc(train_fpr, train_tpr)))
plt.plot(test_fpr, test_tpr, label="test AUC ="+str(auc(test_fpr, test_tpr)))
plt.legend()
plt.xlabel("tpr")
plt.ylabel("fpr")
plt.title("ROC PLOTS for train,test and cv ")
plt.grid()
plt.show()
depth_list = [1,5,10,50]
compute_auc_with_hyper_para_depth(X_train_set_2,y_train,X_test_set_2, y_test, depth_list)
split_list = [5,10,100,500]
compute_auc_with_hyper_para_split(X_train_set_2,y_train,X_test_set_2, y_test, split_list)
print("="*100)
from sklearn.metrics import confusion_matrix
best_t = find_best_threshold(tr_thresholds, train_fpr, train_tpr)
print("Train confusion matrix")
sns.heatmap(confusion_matrix(y_train, predict_with_best_t(y_train_pred_prob, best_t)),annot = True, fmt = "d", cbar=False)
print("Test confusion matrix")
sns.heatmap(confusion_matrix(y_test, predict_with_best_t(y_test_pred_prob, best_t)), annot = True, fmt = "d", cbar=False)
# y_test we have as y_test from train_test_split
# https://www.geeksforgeeks.org/generating-word-cloud-python/
from wordcloud import WordCloud
y_actual = y_test
# y_predicted would be
y_pred = predict_with_best_t(y_test_pred_prob, best_t)
essay_words = " "
essay_ = []
for i in range(len(y_pred)):
if y_pred[i]==1 and y_actual[i]!=y_pred[i]:
essay_.append(x_train_preprocessed_essay[i])
for essay in essay_:
essay_words += essay + " "
wordcloud = WordCloud(width = 800, height = 800,
background_color ='white',
stopwords = stopwords,
min_font_size = 10).generate(essay_words)
# plot the WordCloud image
plt.figure(figsize = (8, 8), facecolor = None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad = 0)
plt.show()
y_actual = y_test
# y_predicted would be
y_pred = predict_with_best_t(y_test_pred_prob, best_t)
prices = []
for i in range(len(y_pred)):
if y_pred[i]==1 and y_actual[i]!=y_pred[i]:
prices.append(X_train['price'].iloc[i])
fig = plt.figure(figsize=(20,10))
fig.suptitle('Price from false positive data points', fontsize=14, fontweight='bold')
ax = fig.add_subplot(111)
ax.boxplot(prices)
ax.set_ylabel('Price')
plt.show()
y_actual = y_test
# y_predicted would be
y_pred = predict_with_best_t(y_test_pred_prob, best_t)
teacher_number_ = []
for i in range(len(y_pred)):
if y_pred[i]==1 and y_actual[i]!=y_pred[i]:
teacher_number_.append(X_train['teacher_number_of_previously_posted_projects'].iloc[i])
fig = plt.figure(figsize=(20,10))
ax = sns.distplot(teacher_number_, hist=True, kde=True,
bins=int(180/5), color = 'darkblue',
hist_kws={'edgecolor':'black'},
kde_kws={'linewidth': 4})
ax.set(xlabel = 'teacher numbers of previously posted projects',ylabel = 'probabilities')
plt.show()
depth = [1,5,10,50]
split = [5,10,100,500]
plot_3d_plot(X_train_set_2, y_train, X_test_set_2, y_test, depth, split)
from prettytable import PrettyTable
summarizer = PrettyTable()
summarizer.field_names = ["vectorizer","Model","Hyper Parameter (max_depth)","Hyper Parameter (min_split)","AUC test"]
summarizer.add_row(["TFIDF","Decision Tree Classifier","10","500","0.60"])
summarizer.add_row(["TFIDF W2V","Decision Tree Classifier","5","500","0.62"])
summarizer.add_row(["Feature Importance","Logistic Regression","0.0001 (reg. parameter)","NA","0.56"])
print(summarizer)